package com.mobilottery.ui;

import org.apache.log4j.Logger;

import com.mobilottery.server.GameUser;
import com.mobilottery.server.User;
import com.mobilottery.server.UserManager;


/**
 * Baking bean for user registration form
 * @author fedor
 */
public class RegisterForm extends ValidationForm
{
    String userName;
    String email;
    String firstName;
    String lastName;
    String password;
    String creditCardNumber;
    
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getCreditCardNumber() {
		return creditCardNumber;
	}
	public void setCreditCardNumber(String creditCardNumber) {
		this.creditCardNumber = creditCardNumber;
	}
	
	protected boolean validateUser()
	{
		if(validateUserName("userName", userName))
		{
			if(UserManager.getInstance().userExists(userName))
			{
				setFieldErorrMessage("userName", "User " + "'" + userName + "' already exists");
				return false;
			}
		}
		return true;
	}
	
	protected void validate()
	{
		validateUser();
		validateMail("email", email);
		validateName("firstName", firstName);
		validateCreditCard("creditCardNumber", creditCardNumber);		
		validatePassword("password", password);
		validateName("lastName", lastName);
	}

	
	public void submit()
	{
		try
		{
			validate();
			if(!hasErrors())
			{
				performSubmit();
			}
		}
		catch(Exception ex)
		{
			Logger.getLogger(getClass()).error("Error processing register form", ex);
			setFieldErorrMessage("form", "Error processing request: " + ex.getMessage());
		}
	}
	
	protected void performSubmit()
	{
		User user = new GameUser(userName, email, firstName, lastName, password, creditCardNumber, false);
		UserManager.getInstance().registerUser(user);
		
	}
	
	public void reset()
	{
		super.reset();
	    userName = "";
	    email = "";
	    firstName = "";
	    lastName = "";
	    password = "";
	    creditCardNumber = "";		
	}
}
